package com.yuenov.open.activitys;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.renrui.libraries.util.ToastUtils;
import com.yuenov.open.R;
import com.yuenov.open.activitys.baseInfo.BaseActivity;
import com.yuenov.open.adapters.BookSelectDownloadMenuListAdapter;
import com.yuenov.open.database.AppDatabase;
import com.yuenov.open.database.tb.TbBookChapter;
import com.yuenov.open.database.tb.TbReadHistory;
import com.yuenov.open.interfaces.IDownloadContentListener;
import com.yuenov.open.model.eventBus.OnDownloadBackUpChangeEvent;
import com.yuenov.open.model.eventBus.OnDownloadMenuFinishChangeEvent;
import com.yuenov.open.model.standard.DownloadBookContentItemInfo;
import com.yuenov.open.utils.FileDownload;
import com.yuenov.open.utils.UtilityBusiness;
import com.yuenov.open.utils.UtilityToasty;
import com.renrui.libraries.util.UtilitySecurity;
import com.renrui.libraries.util.UtilitySecurityListener;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 选择下载页
 */
public class ChapterSelectDownloadListActivity extends BaseActivity implements AdapterView.OnItemClickListener {

    private static final String EXTRA_INT_BOOKID = "bookId";
    private static final String EXTRA_STRING_BOOKNAME = "bookName";
    private static final int REQUEST_CODE=1;
    private int bookId;
    private String bookName;
    private Context context;

    public static Intent getIntent(Context context, String bookName, int bookId) {
        Intent intent = new Intent(context, ChapterSelectDownloadListActivity.class);
        intent.putExtra(EXTRA_INT_BOOKID, bookId);
        intent.putExtra(EXTRA_STRING_BOOKNAME, bookName);
        return intent;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull String name, @NonNull Context context, @NonNull AttributeSet attrs) {
        this.context = context;
        return super.onCreateView(name, context, attrs);
    }

    @BindView(R.id.tvSdTitle)
    protected TextView tvSdTitle;

    @BindView(R.id.lvSdList)
    protected ListView lvSdList;

    private List<String> lis = new ArrayList<>();
    private BookSelectDownloadMenuListAdapter adapter;
    private List<DownloadBookContentItemInfo> myList;

    private static boolean isDownloading = false;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_selectdownload;
    }

    @Override
    protected void initExtra() {
        bookId = UtilitySecurity.getExtrasInt(getIntent(), EXTRA_INT_BOOKID);
        bookName = UtilitySecurity.getExtrasString(getIntent(), EXTRA_STRING_BOOKNAME);

        if (bookId < 1) {
            UtilityToasty.error(R.string.Utility_unknown);
            finish();
        }
    }

    @Override
    protected void initListener() {
        UtilitySecurityListener.setOnItemClickListener(lvSdList, this);
    }

    @Override
    protected void initData() {
        initMyAppTitle(R.string.BSelectDownloadActivity_Title);

        lis.clear();
        lis.add(getString(R.string.BSelectDownloadActivity_item1));
        lis.add(getString(R.string.BSelectDownloadActivity_item2));
        lis.add(getString(R.string.BSelectDownloadActivity_item3));
        lis.add(getString(R.string.BSelectDownloadActivity_item4));

        adapter = new BookSelectDownloadMenuListAdapter(lis);
        lvSdList.setAdapter(adapter);

        if (isDownloading)
            getStatusTip().showDownloadProgress();
    }

    private void download(int afterCounts) {

        if (getStatusTip().isShowing()) {
            UtilityToasty.warning(R.string.BSelectDownloadActivity_downloading);
            return;
        }

        List<TbBookChapter> lisWaitDownloadChapter;

        // 下载全部章节
        if (afterCounts == Integer.MAX_VALUE) {
            lisWaitDownloadChapter = AppDatabase.getInstance().ChapterDao().getAllUnDownloadChapterId(bookId);
        } else {
            // 有阅读记录 从阅读章节开始下载
            // 没有阅读记录 从第一章开始下载
            long startDownloadChapterId = 0;
            TbReadHistory readHistory = AppDatabase.getInstance().ReadHistoryDao().getEntity(bookId);
            if (readHistory != null && readHistory.chapterId > 0) {
                startDownloadChapterId = readHistory.chapterId;
            } else {
                TbBookChapter bookChapter = AppDatabase.getInstance().ChapterDao().getFirstChapter(bookId);
                if (bookChapter != null && bookChapter.chapterId > 0) {
                    startDownloadChapterId = bookChapter.chapterId;
                }
            }

            if (startDownloadChapterId < 1) {
                UtilityToasty.warning(R.string.BSelectDownloadActivity_noDownload);
                return;
            }

            // 获取待下载的章id
            lisWaitDownloadChapter = AppDatabase.getInstance().ChapterDao().getUnDownloadAfterChapterId(bookId, startDownloadChapterId, afterCounts);
        }

        if (UtilitySecurity.isEmpty(lisWaitDownloadChapter)) {
            UtilityToasty.warning(R.string.BSelectDownloadActivity_noDownload);
            return;
        }
        List<Long> lisWaitDownloadChapterId = new ArrayList<>();
        for (int i = 0; i < lisWaitDownloadChapter.size(); i++) {
            if (UtilitySecurity.isEmpty(lisWaitDownloadChapter.get(i).content))
                lisWaitDownloadChapterId.add(lisWaitDownloadChapter.get(i).chapterId);
        }

        isDownloading = true;
        UtilityBusiness.downloadContent(this, bookId, lisWaitDownloadChapterId, false, new IDownloadContentListener() {
            @Override
            public void onDownloadSuccess(List<DownloadBookContentItemInfo> list) {
                isDownloading = false;
                getStatusTip().hideProgress();

                if (!ChapterSelectDownloadListActivity.this.isFinishing()) {
                    UtilityToasty.success(R.string.BSelectDownloadActivity_downloadEnd);
                    if(list==null||list.size()==0)
                        return;
                    myList=list;
                    System.out.println("size1:"+list.size());
                    save();
//                    requestPermission(context);
                }
            }

            @Override
            public void onDownloadLoadFail() {
                isDownloading = false;
                getStatusTip().hideProgress();
            }
        });
    }

    @Subscribe
    public void onEvent(OnDownloadMenuFinishChangeEvent event) {
        getStatusTip().hideProgress();
        Log.e("ohhhhh:", event.bookId + "");
        UtilityToasty.success(R.string.BSelectDownloadActivity_downloadEnd);
    }

    @Subscribe
    public void onEvent(OnDownloadBackUpChangeEvent event) {
        finish();
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

        if (isDownloading || getStatusTip().isShowing())
            return;

        switch (i) {
            case 0:
                download(50);
                break;

            case 1:
                download(100);
                break;

            case 2:
                download(200);
                break;

            case 3:
                download(Integer.MAX_VALUE);
                break;
        }
    }

    private void save(){
        for (int i = 0; i < myList.size(); i++) {
//            System.out.println("result============" + lisWaitDownloadChapter.get(i).chapterName);
            System.out.println("size:"+myList.size());
            String route=context.getExternalFilesDir("").getAbsolutePath();
//            FileDownload.createFileAndSave(route,bookName, myList.get(i).content, "chapter"+(i+1)+".txt");
        }
    }

    private void requestPermission(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // 先判断有没有权限
            if (Environment.isExternalStorageManager()) {
                save();
            } else {
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                intent.setData(Uri.parse("package:" + context.getPackageName()));
                startActivityForResult(intent, REQUEST_CODE);
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 先判断有没有权限
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                save();
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
            }
        } else {
            save();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                save();
            } else {
                ToastUtils.showShort("存储权限获取失败");
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (Environment.isExternalStorageManager()) {
                save();
            } else {
                ToastUtils.showShort("存储权限获取失败");
            }
        }
    }
}
